package com.gxp.system.service.impl;

import com.gxp.common.core.domain.entity.SysUser;
import com.gxp.common.core.text.Convert;
import com.gxp.common.exception.ServiceException;
import com.gxp.common.utils.DateUtils;
import com.gxp.common.utils.StringUtils;
import com.gxp.system.domain.*;
import com.gxp.system.mapper.*;
import com.gxp.system.service.IZknjProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目Service业务层处理
 * 
 * @author zh
 * @date 2024-07-09
 */
@Service
public class ZknjProjectServiceImpl implements IZknjProjectService 
{
    @Autowired
    private ZknjProjectMapper zknjProjectMapper;
    @Autowired
    private ZknjProUserMapper zknjProUserMapper;
    @Autowired
    private ZknjServiceMapper zknjServiceMapper;
    @Autowired
    private ZknjProInstSerMapper zknjProInstSerMapper;
    @Autowired
    private ZknjRequestMapper requestMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ZkInstrumentMapper instrumentMapper;
    @Autowired
    private ZknjServiceMapper serviceMapper;

    /**
     * 查询项目
     * 
     * @param proId 项目主键
     * @return 项目
     */
    @Override
    public ZknjProject selectZknjProjectByProId(Long proId)
    {
        return zknjProjectMapper.selectZknjProjectByProId(proId);
    }

    /**
     * 查询项目列表
     * 
     * @param zknjProject 项目
     * @return 项目
     */
    @Override
    public List<ZknjProject> selectZknjProjectList(ZknjProject zknjProject)
    {
        return zknjProjectMapper.selectZknjProjectList(zknjProject);
    }

    /**
     * 新增项目
     * 
     * @param zknjProject 项目
     * @return 结果
     */
    @Override
    public int insertZknjProject(ZknjProject zknjProject, String managers, String requesters, String services)
    {
        zknjProject.setCreateTime(DateUtils.getNowDate());
        zknjProject.setProStatus(2l);
        zknjProject.setIsLock(0l);
        zknjProject.setApproveType("Add Project");
        int inserted = zknjProjectMapper.insertZknjProject(zknjProject);
        if(zknjProject.getProId() != null){
            String userIds = managers + "," + requesters;
            String[] split = userIds.split(",");
            for (String s : split) {
                ZknjProUser proUser = new ZknjProUser();
                proUser.setUserId(Long.valueOf(s));
                proUser.setPeoId(zknjProject.getProId());
                zknjProUserMapper.insertZknjProUser(proUser);
            }
            //仪器和服务范围
            if(services.indexOf(",") > 0){
                String[] split1 = services.split(",");
                for (String s : split1) {
                    Long serId = Long.valueOf(s);
                    Long instId = zknjServiceMapper.selectZknjServiceBySerId(serId).getInstId();
                    ZknjProInstSer proInstSer = new ZknjProInstSer();
                    proInstSer.setProId(zknjProject.getProId());
                    proInstSer.setInstId(instId);
                    proInstSer.setSerId(serId);
                    zknjProInstSerMapper.insertZknjProInstSer(proInstSer);
                }
            }else {
                Long serId = Long.valueOf(services);
                Long instId = zknjServiceMapper.selectZknjServiceBySerId(serId).getInstId();
                ZknjProInstSer proInstSer = new ZknjProInstSer();
                proInstSer.setProId(zknjProject.getProId());
                proInstSer.setInstId(instId);
                proInstSer.setSerId(serId);
                zknjProInstSerMapper.insertZknjProInstSer(proInstSer);
            }
        }
        return inserted;
    }

    /**
     * 修改项目
     * 
     * @param zknjProject 项目
     * @return 结果
     */
    @Override
    public int updateZknjProject(ZknjProject zknjProject)
    {
        zknjProject.setUpdateTime(DateUtils.getNowDate());
//        ZknjProject projectOld = zknjProjectMapper.selectZknjProjectByProId(zknjProject.getProId());
//        if(projectOld.getProStatus() == 2 || projectOld.getProStatus() == 4){
//            zknjProject.setProStatus(null);
//        }
        return zknjProjectMapper.updateZknjProject(zknjProject);
    }

    /**
     * 批量删除项目
     * 
     * @param proIds 需要删除的项目主键
     * @return 结果
     */
    @Override
    public int deleteZknjProjectByProIds(String proIds)
    {
        Long[] proIdArray = Convert.toLongArray(proIds);
        for (Long proId : proIdArray) {
            //检查project下是否创建request，是，不允许删除，否，可以删除
            if(checkHaveRequest(proId)){
                throw new ServiceException("该项目已经启用，不允许删除");
            }
            ZknjProject project = new ZknjProject();
            project.setProId(proId);
            project.setProStatus(2l);
            project.setApproveType("Delete Project");
            zknjProjectMapper.updateZknjProject(project);
        }
        return 1;
//        return zknjProjectMapper.deleteZknjProjectByProIds(Convert.toStrArray(proIds));
    }

    /**
     * 检查项目下是否拥有服务申请
     */
    private boolean checkHaveRequest(Long proId) {
        ZknjRequest request = requestMapper.checkHaveRequest(proId);
        ZknjRequest requestHistory = requestMapper.checkHaveRequestHistory(proId);
        if(StringUtils.isNotNull(request) || StringUtils.isNotNull(requestHistory)){
            return true;
        }
        return false;
    }

    /**
     * 删除项目信息
     * 
     * @param proId 项目主键
     * @return 结果
     */
    @Override
    public int deleteZknjProjectByProId(Long proId)
    {
        return zknjProjectMapper.deleteZknjProjectByProId(proId);
    }

    /**
     * 根据申请者查询project
     * @param userId
     * @return
     */
    @Override
    public List<ZknjProject> selectZknjProjectByUser(Long userId) {
        return zknjProjectMapper.selectZknjProjectByUser(userId);
    }

    /**
     * 项目审核
     */
    @Override
    public int approve(ZknjProject zknjProject) {
        if(zknjProject.getProStatus() == 3){
            //审核成功，状态更改为 On/Off
            ZknjProject projectOld = zknjProjectMapper.selectZknjProjectByProId(zknjProject.getProId());
            zknjProject.setProStatus(projectOld.getIsLock());
            //判断 Add/Update/Remove
            if(projectOld.getApproveType().equals("Delete Project")){
                //删除关联表
                zknjProUserMapper.deleteZknjProUserByPeoId(zknjProject.getProId());
                zknjProInstSerMapper.deleteZknjProInstSerByProId(zknjProject.getProId());
                return zknjProjectMapper.deleteZknjProjectByProId(zknjProject.getProId());
            }
        }
        return zknjProjectMapper.updateZknjProject(zknjProject);
    }

    /**
     * 项目名校验
     */
    @Override
    public boolean checkProNameUnique(ZknjProject zknjProject) {
        Long proId = zknjProject.getProId() == null ? -1L: zknjProject.getProId();
        ZknjProject project = zknjProjectMapper.checkProNameUnique(zknjProject.getProName());
        if(StringUtils.isNotNull(project) && project.getProId().longValue() != proId.longValue()){
            return false;
        }
        return true;
    }

    /**
     * 获取managers字符串
     */
    @Override
    public String getManagersByProId(Long proId) {
        List<SysUser> sysUsers = sysUserMapper.selectUserByProId(proId);
        //TODO：Role analyses manager不能删除
        List<String> users = sysUsers.stream().filter(user -> user.getRoles().get(0).getRoleId() == 102l).map(SysUser::getUserName).collect(Collectors.toList());
        return String.join(",", users);
    }

    /**
     * 获取requesters字符串
     */
    @Override
    public String getRequestersByProId(Long proId) {
        List<SysUser> sysUsers = sysUserMapper.selectUserByProId(proId);
        //TODO：Role requester不能删除
        List<String> users = sysUsers.stream().filter(user -> user.getRoles().get(0).getRoleId() == 101l).map(SysUser::getUserName).collect(Collectors.toList());
        return String.join(",", users);
    }

    /**
     * 获取instruments字符串
     */
    @Override
    public String getInstrumentsByProId(Long proId) {
        List<ZkInstrument> instrumentList = instrumentMapper.selectZkInstrumentByProId(proId);
        if(instrumentList == null || instrumentList.isEmpty()){
            return "All";
        }
        List<String> instNames = instrumentList.stream().map(ZkInstrument::getInstName).collect(Collectors.toList());
        return String.join(",", instNames);
    }

    /**
     * 获取services字符串
     */
    @Override
    public String getServicesByProId(Long proId) {
        List<ZknjService> serviceList = serviceMapper.selectZknjServicesByProId(proId);
        if(serviceList == null || serviceList.isEmpty()){
            return "All";
        }
        List<String> serNames = serviceList.stream().map(ZknjService::getSerName).collect(Collectors.toList());
        return String.join(",", serNames);
    }
}
